<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="作业名称" prop="homeworkName">
        <el-input
          v-model="queryParams.homeworkName"
          placeholder="请输入作业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <template v-if="userType !== '4'">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:teacherHomework:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:teacherHomework:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </template>

    <el-table v-loading="loading" :data="teacherHomeworkList" @selection-change="handleSelectionChange">
      <template v-if="userType !== '4'">
        <el-table-column type="selection" width="55" align="center" />
      </template>
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="作业名称" align="center" prop="homeworkName" />
      <el-table-column label="科目类别" align="center" prop="courseName" />
      <el-table-column label="创建人" align="center" prop="createNickName" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="截止时间" align="center" prop="closeTime" >
        <template slot-scope="scope">
          {{ dealTime(scope.row.closeTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <template v-if="userType === '4'">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['system:teacherHomework:edit']"
            > 查看</el-button>
          </template>
          <template v-else>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleCheckHomeWork(scope.row)"
              v-hasPermi="['system:teacherHomework:edit']"
            > 查看作业</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:teacherHomework:edit']"
            > 修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:teacherHomework:remove']"
            > 删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
      title="查看作业完成情况"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
    >
      <el-table v-loading="loadingHomeWork" :data="homeworkDetailList">
        <el-table-column label="学生" align="center" prop="studentUserName" />
        <el-table-column label="完成时间" align="center" prop="finishTime" >
          <template slot-scope="scope">
            {{ scope.row.createTime ? dealTime(scope.row.createTime) : '--' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              :disabled="!scope.row.uploadHomeworkUrl"
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="downloadImg(scope.row)"
            > 下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改老师布置的家庭作业对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级" prop="classNumber">
          <el-select v-model="form.classId" :disabled="isDisabled" filterable placeholder="请选择班级">
            <el-option
              v-for="item in claassList"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="科目类别" prop="courseId">
          <el-select v-model="form.courseType" :disabled="isDisabled" filterable placeholder="请选择作业科目">
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.courseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="截止时间" prop="closeTime">
          <el-date-picker
            v-model="form.closeTime"
            type="datetime"
            :disabled="isDisabled"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="作业名称" prop="homeworkName">
          <el-input v-model="form.homeworkName" :disabled="isDisabled" placeholder="请输入作业名称" />
        </el-form-item>
        <el-form-item label="上传作业" prop="homeworkName">
          <el-upload
            :disabled="isDisabled"
            class="upload-demo"
            :action="uploadUrl"
            :headers="headers"
            :file-list="fileList"
            :on-success="handleSuccess"
          >
            <el-button size="small" :disabled="isDisabled" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">可上传 word、pdf、jpg、png 文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template v-if="userType !== '4'">
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listTeacherHomework, getTeacherHomework, delTeacherHomework, addTeacherHomework, updateTeacherHomework } from "@/api/system/teacherHomework";
import {listClaass} from "@/api/system/claass";
import {listType} from "@/api/system/courseType";
import {getToken} from "@/utils/auth";
import {listStudentHomework} from "@/api/system/studentHomework";

export default {
  name: "TeacherHomework",
  data() {
    return {
      headers: { 'Authorization': 'Bearer ' + getToken() },
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 老师布置的家庭作业表格数据
      teacherHomeworkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classId: null,
        courseType: null,
        homeworkName: null,
        homeworkUrl: null,
        createUser: null,
        updateName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      claassList: [],
      subjectList: [],
      userType: '',
      isDisabled: false,
      drawer: false,
      loadingHomeWork: true,
      homeworkDetailList: []
    };
  },
  created() {
    this.getList();
    this.userType = localStorage.getItem('userType')
  },
  methods: {
    downloadImg(row) {
      if (!row.uploadHomeworkUrl) {
        return
      }
      const link = document.createElement('a');
      link.href = row.uploadHomeworkUrl; // 替换为实际图片路径
      link.download = row.uploadHomeworkName;
      if (row.uploadHomeworkUrl.indexOf('.png') !== -1 || row.uploadHomeworkUrl.indexOf('.jpg') !== -1) {
        link.target = '_blank'
      }
      link.click()
    },
    dealTime(time) {
      return time.split('T').join(' ').split('.')[0]
    },
    handleSuccess(response) {
      this.form.homeworkUrlName = response.originalFilename
      this.form.homeworkUrl =  process.env.VUE_APP_BASE_API + response.fileName
    },
    /** 查询老师布置的家庭作业列表 */
    getList() {
      this.loading = true;
      listClaass({
        pageNum: 1,
        pageSize: 100,
      }).then(response => {
        this.claassList = response.rows;
      });
      listType({
        pageNum: 1,
        pageSize: 100,
      }).then(res => {
        this.subjectList = res.rows
      })
      listTeacherHomework(this.queryParams).then(response => {
        this.teacherHomeworkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        classId: null,
        courseType: null,
        homeworkName: null,
        homeworkUrl: null,
        createUser: null,
        createTime: null,
        updateName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增作业";
    },
    /** 查看作业完成情况 */
    handleCheckHomeWork(row) {
      console.log('row', row)
      this.drawer = true
      this.loadingHomeWork = true
      listStudentHomework({
        startPage: false,
        teacherUploadId: row.id
      }).then(response => {
        this.homeworkDetailList = response.rows;
        this.loadingHomeWork = false
      });
    },
    /** 关闭查看作业完成情况 */
    handleClose() {
      this.homeworkDetailList = []
      this.drawer = false
      this.loadingHomeWork = true
    },
    /** 下载作业 */
    handleDownloadHomeWork(row) {
      console.log('row', row)
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getTeacherHomework(id).then(response => {
        this.form = response.data;
        this.fileList = [{
          name: this.form.homeworkUrlName,
          url: this.form.homeworkUrl
        }]
        this.isDisabled = true
        this.open = true;
        this.title = "查看作业";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTeacherHomework(id).then(response => {
        this.form = response.data;
        this.fileList = [{
          name: this.form.homeworkUrlName,
          url: this.form.homeworkUrl
        }]
        this.open = true;
        this.title = "修改作业";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log('this.form', this.form)
          if (this.form.id != null) {
            updateTeacherHomework(this.form).then(() => {
              this.fileList = []
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeacherHomework(this.form).then(() => {
              this.fileList = []
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除【${row.homeworkName}】`).then(function() {
        return delTeacherHomework(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/teacherHomework/export', {
        ...this.queryParams
      }, `teacherHomework_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.el-drawer__header > :first-child {
  font-size: 16px;
}
</style>
